<template>
  <div id="app">
    body: {{ data.body }} <br>
    id: {{ data.id }} <br>
    title: {{ data.title }} <br>
    userId: {{ data.userId }} <br>
  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      data: {
        body: "",
        id: "",
        title: "",
        userId: "",
      }
    }
  },
  created() {
    /**
     * 监听刷新事件,如果 F5 刷新了,就将数据写入到 sessionStorage
     */
    window.addEventListener('unload', () => {
      window.sessionStorage.setItem("vuex", JSON.stringify(this.$store.state))
    })

    /**
     * 从 sessionStorage 获取 vuex,如果值不为 null,对应的将值写入到对应的 state 中去
     */
    let data = window.sessionStorage.getItem("vuex");
    if (data != null) {
      let store = JSON.parse(data);
      this.$store.commit("setName", store.user.name)
    }
  },
  mounted() {
    this.axios.get("/posts/1")
        .then((data) => {
          this.data = data
        })
  }
}
</script>

<style lang="less">

</style>
